﻿Public Class GlyphFilterTextBox
    Inherits TextBox

    Public Shared ReadOnly ClearTextCommand As RoutedUICommand = New RoutedUICommand("Clear Text", "ClearText", GetType(GlyphFilterTextBox))

    Public Shared ReadOnly CollectionProperty As DependencyProperty = _
        DependencyProperty.Register( _
            "Collection", GetType(ICollectionView), GetType(GlyphFilterTextBox), _
            New FrameworkPropertyMetadata( _
                Nothing, _
                Sub(d, e) CType(d, GlyphFilterTextBox).OnCollectionChanged(CType(e.OldValue, ICollectionView), CType(e.NewValue, ICollectionView))))

    Public Property Collection As ICollectionView
        Get
            Return CType(GetValue(CollectionProperty), ICollectionView)
        End Get
        Set(ByVal value As ICollectionView)
            SetValue(CollectionProperty, value)
        End Set
    End Property

    Private Sub OnCollectionChanged(oldValue As ICollectionView, newValue As ICollectionView)
        If oldValue IsNot Nothing Then
            oldValue.Filter = Nothing
        End If
        If newValue IsNot Nothing Then
            newValue.Filter = AddressOf Filter
        End If
    End Sub

    Private Function Filter(o As Object) As Boolean
        If Not TypeOf o Is GlyphViewModel Then Return False
        Dim g = DirectCast(o, GlyphViewModel)
        Dim t = Text.ToUpper

        If g.Char.ToString.ToUpper.Contains(t) Then Return True
        If t.Contains(g.Char.ToString.ToUpper) Then Return True
        If g.CharCode.ToString.ToUpper.Contains(t) Then Return True
        If g.CharCodeHex.ToUpper.Contains(t) Then Return True
        Return False
    End Function

    Public Sub New()
        CommandBindings.Add( _
            New CommandBinding( _
                ClearTextCommand, _
                Sub(sender, e) Text = "", _
                Sub(sender, e) e.CanExecute = True))
    End Sub

    Protected Overrides Sub OnTextChanged(e As TextChangedEventArgs)
        MyBase.OnTextChanged(e)

        Dim c = Collection
        If c IsNot Nothing Then
            c.Refresh()
        End If
    End Sub

End Class
